package com.example.util.aes256;

import java.math.BigInteger;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.KeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;



import android.util.Log;

public class SecurityUtils {
  public static String encrypt(String message,String ivStr,String keyP) throws Exception{
	    SecretKeySpec sks = new SecretKeySpec(keyP.getBytes(),"AES");
	    Cipher c = Cipher.getInstance("AES/CBC/ZeroBytePadding"); 
	    IvParameterSpec ivp = new IvParameterSpec(ivStr.getBytes("UTF-8"));
	    c.init(Cipher.ENCRYPT_MODE, sks,ivp);
	    byte[] ciphertext = c.doFinal(message.getBytes("UTF-8"));
	    
	    String encrytedHex = bin2hex(ciphertext);
	    Log.i("CE", new String(encrytedHex));
        return encrytedHex;
	  
  }
  public static String decrypt(String ciphertext,String iv,String secret) throws Exception {
	    byte[] cipherIn = HexEncoder.decodeHex(ciphertext.toCharArray());
	    SecretKeySpec sks = new SecretKeySpec(secret.getBytes(),"AES");
	    Cipher cipher = Cipher.getInstance("AES/CBC/ZeroBytePadding");
	    cipher.init(Cipher.DECRYPT_MODE, sks, new IvParameterSpec(iv.getBytes("UTF-8")));
	    byte[] cipherByte = cipher.doFinal(cipherIn);
	    String encrytedHex = new String(cipherByte);
	    Log.i("CE", new String(cipherByte));
	return encrytedHex;
	  }
  static String bin2hex(byte[] data) {
	  return String.format("%0" + (data.length * 2) + 'x', new BigInteger(1, data));
	}

}